import re
import uuid
from urllib import request

import bula as bula
import pdfplumber
import tabula
import pandas as pd
import time
from flask import Blueprint, jsonify

from interface import db
from interface.Setting import UPLOAD_FOLDER_CVS
from interface.models.test import User

testview = Blueprint('textview', __name__, url_prefix='/api/UserService')


# 测试数据库插入数据
@testview.route("/addUser", methods=['POST'])
def getadmin():
    # 数据库插入数据
    user = User()
    user.name = '1111'
    db.session.add(user)
    db.session.flush()
    db.session.commit()
    db.session.close()
    return jsonify({'msg': '成功'})


@testview.route("/getpdfsssssss", methods=['POST'])
def getpdf():
    path = 'C:\\Users\\2019\\Desktop\\排污许可证申请表.pdf'
    pdf = pdfplumber.open(path)

    for page in pdf.pages:
        print(page.extract_text())
        for pdf_table in page.extract_tables():
            table = []
            cells = []
            for row in pdf_table:
                if not any(row):
                    # 如果一行全为空，则视为一条记录结束
                    if any(cells):
                        table.append(cells)
                        cells = []
                elif all(row):
                    # 如果一行全不为空，则本条为新行，上一条结束
                    if any(cells):
                        table.append(cells)
                        cells = []
                    table.append(row)
                else:
                    if len(cells) == 0:
                        cells = row
                    else:
                        for i in range(len(row)):
                            if row[i] is not None:
                                cells[i] = row[i] if cells[i] is None else cells[i] + row[i]
            for row in table:
                print([re.sub('\s+', '', cell) if cell is not None else None for cell in row])
            print('---------- 分割线 ----------')

    pdf.close()

    return ""




# 使用tabula读取PDF中表格数据  只读取PDF中 表格的数据
@testview.route("/getPdfData", methods=['POST'])
def getPdfData():
    msg = ''
    print(UPLOAD_FOLDER_CVS)

    df = tabula.read_pdf("C:\\Users\\2019\\Desktop\\排污许可证申请表.pdf", encoding='gbk', pages='all')
    print(df)
    DATA = tabula.convert_into("C:\\Users\\2019\\Desktop\\排污许可证申请表.pdf",
                               "E:\\ls_project\\python\\test\interface\\uploads\\" + str(uuid.uuid1()) + ".json",
                               output_format="json", pages='all')
    print(DATA)
    msg = '成功'
    return jsonify({'msg': msg})


# pdfplumber  读取PDF  读取PDF中所有数据
@testview.route('/getPDF', methods=['POST'])
def getPDF():
    msg = ''
    with pdfplumber.open('C:\\Users\\2019\\Desktop\\排污许可证申请表.pdf')as pdf:

        for i in range(len(pdf.pages)):
            page = pdf.pages[i]
            for table in page.extract_tables():
                print(table)
                # tb = pd.DataFrame(table[1:], columns=table[0], index=None)
                # print(tb)

    # tb.to_excel('C:\\Users\\2019\\Desktop\\test.xlsx', index=False)

    return msg
